<?php

namespace App\Jobs;

use App\Enums\RoomConnectionEnum;
use App\Repositories\RoomConnectionRepository;
use App\Services\Tools\IdempotentConsume;
use Illuminate\Support\Facades\Log;

class RoomConnectionJob extends Job
{

    protected $data;
    const jobName = 'RoomConnectionJob';

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (env('APP_ENV') != 'production') {
            Log::error('roomConnectionJob:' . json_encode(['time' => getMillisecond(), 'data' => $this->data]));
        }
        $idempotentConsumeServer = new IdempotentConsume();
        $connection = new RoomConnectionRepository();
        try {
            $data = $this->data;
            if ($data['type'] == RoomConnectionEnum::BEGIN_TIMEOUT) {
                $uk = 'BEGIN_TIMEOUT' . $data['id'] ?? '';
                if ($idempotentConsumeServer->checkIdempotentRedisKey(self::jobName, $uk)) {
                    $connection->beginTimeout($data['id']);
                }

            } elseif ($data['type'] == RoomConnectionEnum::END_TIMEOUT) {
                $connection->endTimeout($data['id']);

            } elseif ($data['type'] == RoomConnectionEnum::DELAYED_TIMEOUT) {
                $connection->delayedHandle($data['id']);
            } elseif ($data['type'] == RoomConnectionEnum::BEGIN_TIME) {
                $uk = 'BEGIN_TIME' . $data['id'] ?? '';
                if ($idempotentConsumeServer->checkIdempotentRedisKey(self::jobName, $uk)) {
                    $connection->beginTime($data['id']);
                }
            }
        } catch (\Exception $exception) {
            $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName, $uk);
            Log::error('roomConnectionJob:' . $exception->getMessage());
        }
    }

}
